<?php

/**
 * Action类
 *
 * @package lib
 * @subpackage core
 * @author 张立冰 <roast@php.net>
 */
class Action {
	
	/**
	 * 应用程序类
	 * @var Application
	 * @access protected
	 */
	var $app;
	
	/**
	 * 应用信息-应用-缓存前缀
	 */
	const APP_MM_PRE = 'APP_DETAIL_';
	
	/**
	 * 应用信息-用户-缓存前缀
	 */
	const USER_MM_PRE = 'APP_USER_';
		
	
	/**
	 * 生成TOKEN的COOKIE
	 *
	 */
	function token()
	{
       	$sign = md5(LOGIN_VERSION . $this->app->cfg['rsa']['prikey'] . $_SESSION['UserId'] . $_SESSION['UID'] . $_SESSION['Nick'] . $_SERVER['HTTP_USER_AGENT'] . $this->app->ip());
        $token = base64_encode(serialize(array($_SESSION['UserId'], $_SESSION['UID'], $_SESSION['Nick'], $sign)));	        
		setcookie('_token', $token);	
	}
	
	
	/**
	 * 构造函数
	 *
	 * @param Application &$app 应用程序类
	 */
	function __construct(& $app) 
	{
		$this->app = $app;
		
//		$this->checkSign();
		
		if ((LOGIN_CHECK === true) && empty($_SESSION['UserId']))
		{
			$arr_data = @unserialize(@base64_decode($_COOKIE['_token']));
			
			if (count($arr_data) == 4)
			{
				$sign = md5(LOGIN_VERSION . $app->cfg['rsa']['prikey'] . $arr_data[0]. $arr_data[1]. $arr_data[2] . $_SERVER['HTTP_USER_AGENT'] . $app->ip());
				if ($sign == $arr_data[3])
				{
					$_SESSION['UserId'] = $arr_data[0];
					$_SESSION['UID'] = $arr_data[1];
					$_SESSION['Nick'] = $arr_data[2];
				}
			}

			if (empty($_SESSION['UserId']))
			{
				exit('{"status":0, "message":"' . _T('请您登录后再进行尝试') . '","type":1}');
			}
		}
	}
	
	/**
	 * 默认Action
	 */
	function doDefault() { /* nothing */ }
	
	
	/**
	 * 原使用FirePHP做调试，已去除
	 *
	 * @return void
	 */
	function debug()
	{
		return true;				
	}
	
	
	/**
	 * 输出验证输出处理 
	 */
	function doCode() 
	{
		import('util.ValidateCode');
		$img = new ValidateCode();
		
		/** 设置字体文件与临时目录 **/
		$img->font_dir = $this->app->cfg['path']['fonts'];
		$img->temp_dir = $this->app->cfg['path']['temp'];
		
		$img->session_name='VALIDATE_CODE';
		$img->background_color(array('#FEFDCF','#DFFEFF','#FFEEE1','#E1F4FF'));
		$img->grid_color(array('#FAD1AD','#FFD9FB','#D1D1E0'));
		$img->text_color(array('#801D00','#5C0497','#0289B0'));
		$img->overlap_text(false);
		$img->random_y_factor(4);
		$img->string_length(4);
		$img->frame_number(3);
		$img->frame_delay(80);
		$img->generate();
	}
	
	
	/**
	 * 验证验证码是否正确
	 *
	 * @param string $code
	 * @return boolean
	 */
	function _checkCode($code)
	{
		if ($code && $code == $_SESSION['VALIDATE_CODE'])
		{
			unset($_SESSION['VALIDATE_CODE']);
			return true;
		}
		else 
			return false;
	}
	
	
	/**
	 * 执行SOAP请求，返回请求得到的数据段切分为数组,简单方法
	 *
	 * @param String $interface WS接口地址
	 * @param String $uri SOAP调用的地址
	 * @param String $op SOAP调用的方法
	 * @param Array $args 传递的参数数据
	 * @param Array $headers 传递的头信息参数
	 * @param Array $headers 传递的头信息参数
	 * @param String $xmlns xmlns名称,默认为tempuri.org
	 * 
	 * @return Array|false	false表示调用失败，否则返回查询到的数据数组 
	 */
    function _soap($interface, $uri, $op, $args, $headers = '', $xmlns = '', $res = '')
    {
        $fp = fsockopen($interface, 80, $errno, $errstr, 30);
        if (!$fp)
            return false;
        else
        {
        	$xmlns = empty($xmlns) ? 'http://tempuri.org/' : $xmlns;
        	
            $content .= '<?xml version="1.0" encoding="utf-8"?>';
            $content .= '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
            
            if (is_array($headers))
            {
            	$content .= '<soap:Header><SecurityHeader xmlns="http://' . $xmlns . '/">';
    			foreach ($headers as $key=>$value)
    			{
    				$content .= '<' . $key . '>' . $value . '</' . $key . '>';
    			}
    			$content .= '</SecurityHeader></soap:Header>';
            }
            
            if (is_array($args))
            {
              	$content .= '<soap:Body>';
	            $content .= '<' . $op . ' xmlns="http://' . $xmlns . '/">';
	            if ( is_array($args))
	            {
	                foreach ( $args as $key=>$value)
	                    $content .= '<' . $key . '>' . $value . '</' . $key . '>';
	            }
	            $content .= '</' . $op . '>';
	            $content .= '</soap:Body>';          	
            }
            
            $content .= '</soap:Envelope>';
            
            $out = "POST /" . $uri . " HTTP/1.1\r\n";
            $out .= "Host: " . $interface . "\r\n";
            $out .= "Content-Type: text/xml; charset=utf-8\r\n";
            $out .= "Content-Length: " . strlen($content) . "\r\n";
            $out .= "SOAPAction: \"http://$xmlns/" . $op . "\"\r\n\r\n";

            fwrite($fp, $out . $content);
            sleep(1);
            
            $ret = fread($fp, 10240);
            fclose($fp);
            
            /* 如果要求有返回，则直接则SOAP调用的数据返回 */
            if (!empty($res))
            	return $ret;
            	
            if ( preg_match('/<soap:Body>(.+)<\/soap:Body>/', $ret, $mc) )
                preg_match_all('/<([^>\/]+)>([^>\/]+)<\/([^>\/]+)>/', $mc[1], $tmp);
            
            if ( count($tmp) != 4 )
                return false;
            else
                return array_combine($tmp[1], $tmp[2]);
        }
    }
    
    /**
     * 接口签名
     * @return unknown_type
     */
    function checkSign()
    {
    	if(!empty($_SESSION['uid']) && $_SERVER['REQUEST_METHOD'] == 'POST' && !$_SESSION['debug'])
    	{
			$mc = $this->app->cache('memcached', $this->app->cfg['memcache']);
	    	$_t = $mc->increment('SIGN_'.$_SESSION['uid']);
	    	$_t--;
	    	$str1 = md5($_t . $_SESSION['uid'] . $this->app->cfg['sign']['secret']);
			$str2 = md5($str1 . $_t);
			$_s = substr($str1, 0,4) . $str2 . substr($str1, 8, 4);
			
			if($_s != $_POST['_s'])
			{
				$log = $this->app->log('cheat/cheat');
				$log->setData(array($_SERVER['REQUEST_URI'], $_SESSION['uid'], $_GET['do'], $_POST['_s'], $_POST['_t'], $_t), date('Y-m-d H:i:s'))->write();
			}
    	}
    }
    
    /**
     * 初始化
     * @return unknown_type
     */
    function initSign()
    {
    	$mc = $this->app->cache('memcached', $this->app->cfg['memcache']);
	    $_t = time();
	    $mc->set('SIGN_'.$_SESSION['uid'], $_t);
	    return $_t;
    }
    
    
    
    //任冬
    function addCache()
    { 	
    	
		//缓存时间 单位：秒。 缓存1个月
		$cache_time = 30 * 24 * 3600;
		$now = time();
		
		if (!empty ($_SERVER['HTTP_IF_MODIFIED_SINCE']))
		{
			$oldtime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
			if ( ($now - $oldtime) < $cache_time)
			{
				header('HTTP/1.1 304 Not Modified');
				header('Cache-Control: max-age=' . $cache_time);
				header('Pragma: ');
				header("Date: " . gmdate("D, d M Y H:i:s", $now));
				header('Last-Modified: ' . $_SERVER['HTTP_IF_MODIFIED_SINCE']);
				exit(0);
			}
		}
		
		
		/**
		* 增加客户端缓存
		*/
		header('Cache-Control: max-age=' . $cache_time);
		header('Pragma: ');
		header("Date: " . gmdate("D, d M Y H:i:s", $now));
		header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $now) . ' GMT');
		header('Expires: ' . gmdate ("D, d M Y H:i:s", $now + $cache_time). " GMT");
    	
    }
    
    function outFail($message)
    {
    	exit(json_encode(array('status'=>0, 'message'=>_T($message))));
    }
}
?>